package com.icongyou.enterprise.talent_analysis.service;

import com.icongyou.enterprise.data_aggregation.entity.UserEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_analysis.entity.PortraitResponse;
import com.icongyou.enterprise.talent_analysis.entity.StudentInsight;
import com.icongyou.enterprise.talent_analysis.entity.TaskCategoryAnalysis;
import com.icongyou.enterprise.talent_analysis.service.impl.AIInsightServiceImpl;
import com.icongyou.enterprise.talent_analysis.service.impl.StudentFeatureExtractor;
import com.icongyou.enterprise.talent_analysis.service.support.AIClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

/**
 * AI洞察服务测试
 */
@ExtendWith(MockitoExtension.class)
@DisplayName("AI洞察服务测试")
class AIInsightServiceImplTest {

    @Mock
    private DataAggregationService dataAggregationService;

    @Mock
    private PortraitService portraitService;

    @Mock
    private AIPortraitEvaluationService aiPortraitService;

    @Mock
    private HrTemplatePreferenceService preferenceService;

    @Mock
    private WordCloudService wordCloudService;

    @Mock
    private AIClient aiClient;

    @Mock
    private StudentFeatureExtractor featureExtractor;

    private AIInsightServiceImpl service;

    @BeforeEach
    void setUp() {
        service = new AIInsightServiceImpl(
            dataAggregationService,
            portraitService,
            aiPortraitService,
            preferenceService,
            wordCloudService,
            aiClient,
            featureExtractor
        );
    }

    @Test
    @DisplayName("生成学生洞察 - 完整流程")
    void testGenerateStudentInsight_CompleteFlow() {
        // Arrange
        String studentId = "student-1";
        String hrUserId = "hr-1";

        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortrait();

        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);
        when(aiClient.chat(anyString())).thenReturn("[]");

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, hrUserId);

        // Assert
        assertNotNull(result);
        assertEquals(studentId, result.getStudentId());
        assertEquals(student.getRealName(), result.getStudentName());
        assertEquals(student.getMajor(), result.getMajor());
        assertNotNull(result.getGeneratedTime());
        assertEquals("GPT-4", result.getAiModelVersion());
        
        // 验证调用了必要的服务
        // dataAggregationService.getStudentById 会被多个内部方法调用
        verify(dataAggregationService, atLeastOnce()).getStudentById(studentId);
        verify(portraitService, atLeastOnce()).computeDefaultPortrait(studentId);
    }

    @Test
    @DisplayName("生成学生洞察 - 学生不存在")
    void testGenerateStudentInsight_StudentNotFound() {
        // Arrange
        when(dataAggregationService.getStudentById(anyString())).thenReturn(null);

        // Act
        StudentInsight result = service.generateStudentInsight("nonexistent", "hr-1");

        // Assert
        assertNotNull(result);
        assertEquals("nonexistent", result.getStudentId());
        assertNull(result.getStudentName());
        
        // 学生不存在时应该直接返回,不调用其他服务
        verify(portraitService, never()).computeDefaultPortrait(anyString());
    }

    @Test
    @DisplayName("生成学生洞察 - 有HR模板偏好")
    void testGenerateStudentInsight_WithHrPreference() {
        // Arrange
        String studentId = "student-1";
        String hrUserId = "hr-1";

        UserEntity student = createMockStudent();
        PortraitResponse customPortrait = createMockPortrait();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(preferenceService.getCurrentTemplateId(hrUserId)).thenReturn("custom-template-1");
        when(aiPortraitService.computeCustomPortrait(studentId, "custom-template-1"))
            .thenReturn(customPortrait);

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, hrUserId);

        // Assert
        assertNotNull(result);
        
        // 应该使用HR的自定义模板而不是默认模板
        verify(preferenceService, atLeastOnce()).getCurrentTemplateId(hrUserId);
        verify(aiPortraitService, atLeastOnce()).computeCustomPortrait(studentId, "custom-template-1");
        // 即使使用自定义模板，其他内部方法可能仍会调用 getStudentById
        verify(dataAggregationService, atLeastOnce()).getStudentById(studentId);
    }

    @Test
    @DisplayName("分析任务类别表现 - 正常场景")
    void testAnalyzeTaskCategoryPerformance() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(createMockPortrait());

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getTaskCategoryAnalysis());
        TaskCategoryAnalysis analysis = result.getTaskCategoryAnalysis();
        
        // 验证包含任务类别统计
        assertNotNull(analysis.getPerformanceByType());
    }

    @Test
    @DisplayName("提取维度亮点 - 识别高分维度")
    void testExtractDimensionHighlights() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortraitWithHighScores();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getDimensionHighlights());
        assertTrue(result.getDimensionHighlights().size() > 0,
            "应该识别出至少一个维度亮点");
    }

    @Test
    @DisplayName("生成岗位推荐 - AI调用成功")
    void testGenerateJobRecommendations_AISuccess() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortrait();
        
        String aiResponse = """
            [{
                "jobTitle": "软件开发工程师",
                "jobCategory": "技术研发",
                "matchScore": 85.5,
                "recommendationReason": "技术能力突出"
            }]
            """;
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);
        when(aiClient.chat(anyString())).thenReturn(aiResponse);

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getJobRecommendations());
        assertTrue(result.getJobRecommendations().size() > 0,
            "应该解析出至少一个岗位推荐");
        
        var firstJob = result.getJobRecommendations().get(0);
        assertEquals("软件开发工程师", firstJob.getJobTitle());
        assertEquals("技术研发", firstJob.getJobCategory());
        assertEquals(85.5, firstJob.getMatchScore());
    }

    @Test
    @DisplayName("生成岗位推荐 - AI调用失败降级")
    void testGenerateJobRecommendations_AIFailureFallback() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortrait();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);
        when(aiClient.chat(anyString()))
            .thenThrow(new RuntimeException("AI服务异常"));

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getJobRecommendations());
        // AI失败时应该有降级的规则推荐
        assertTrue(result.getJobRecommendations().size() > 0,
            "AI失败时应该返回规则生成的推荐");
    }

    @Test
    @DisplayName("分析优缺点 - 正常场景")
    void testAnalyzeStrengthsAndWeaknesses() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortrait();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getStrengths());
        assertNotNull(result.getWeaknesses());
        
        // 应该至少识别出一些优点或缺点
        assertTrue(result.getStrengths().size() > 0 || result.getWeaknesses().size() > 0,
            "应该识别出学生的优点或缺点");
    }

    @Test
    @DisplayName("生成综合评价 - 包含关键信息")
    void testGenerateOverallEvaluation() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        PortraitResponse portrait = createMockPortrait();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(portrait);

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getOverallEvaluation());
        assertFalse(result.getOverallEvaluation().isEmpty(),
            "综合评价不应为空");
    }

    @Test
    @DisplayName("生成职业发展建议 - 正常场景")
    void testGenerateCareerAdvice() {
        // Arrange
        String studentId = "student-1";
        UserEntity student = createMockStudent();
        
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(portraitService.computeDefaultPortrait(studentId)).thenReturn(createMockPortrait());
        when(aiClient.chat(anyString())).thenReturn("建议加强技术学习和项目实践");

        // Act
        StudentInsight result = service.generateStudentInsight(studentId, null);

        // Assert
        assertNotNull(result.getCareerAdvice());
        assertFalse(result.getCareerAdvice().isEmpty(),
            "应该生成职业发展建议");
    }

    // ==================== Helper Methods ====================

    private UserEntity createMockStudent() {
        UserEntity student = new UserEntity();
        student.setId("student-1");
        student.setRealName("张三");
        student.setMajor("软件工程");
        student.setClassName("软件2101");
        return student;
    }

    private PortraitResponse createMockPortrait() {
        PortraitResponse portrait = new PortraitResponse();
        portrait.getLabels().add("技术能力");
        portrait.getLabels().add("问题解决");
        portrait.getLabels().add("学习能力");
        portrait.getScores().add(4.5);
        portrait.getScores().add(4.0);
        portrait.getScores().add(3.8);
        return portrait;
    }

    private PortraitResponse createMockPortraitWithHighScores() {
        PortraitResponse portrait = new PortraitResponse();
        portrait.getLabels().add("技术能力");
        portrait.getLabels().add("团队协作");
        portrait.getScores().add(4.8);  // 高分
        portrait.getScores().add(4.7);  // 高分
        return portrait;
    }
}
